import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:kasax/commons/commons.dart';
import 'package:kasax_demos2/entry/entrys.dart';
import 'package:kasax_demos2/providers/data_providers.dart';
import 'package:kasax_demos2/widgets/posts_widgets.dart';

/// 基于http: ^0.13.3 & FutureBuilder
/// https://pub.dev/packages/http/versions/0.13.3/example
/// https://reqbin.com/ 在线请求测试
class HttpDemo3 extends StatefulWidget {
  const HttpDemo3({Key? key}) : super(key: key);

  @override
  _HttpDemo3State createState() => _HttpDemo3State();
}

class _HttpDemo3State extends State<HttpDemo3> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(child: buildContent2());
  }

  buildContent() {
    return FutureBuilder(
      builder: (BuildContext context, AsyncSnapshot<List<Posts>> asyncsnapshot) {
        return buildPageContent(asyncsnapshot);
      },
      future: DataProvider.getInstance().fetchAllPosts(),
    );
  }

  buildContent2() {
    return PostsListWidget((BuildContext context, AsyncSnapshot<List<Posts>> snapshot) {
      log("buildContent2 PostsListWidget buildListView run...");
      return buildListView(snapshot);
    });
  }

  buildPageContent(AsyncSnapshot<List<Posts>> asyncsnapshot) {
    var connectionState = asyncsnapshot.connectionState;
    log("connectionState: $connectionState");
    if (connectionState == ConnectionState.waiting) {
      return buildLoadingWidget();
    } else if (connectionState == ConnectionState.done) {
      return (asyncsnapshot.data == null || asyncsnapshot.data!.isEmpty)
          ? buildLoadingWidget()
          : buildListView(asyncsnapshot);
    }
  }

  buildListView(AsyncSnapshot<List<Posts>> asyncsnapshot) {
    return ListView(
      children: asyncsnapshot.data!
          .map<Widget>((e) => Padding(
                padding: EdgeInsets.only(top: 15),
                child: ListTile(
                  title: Text(e.title),
                  subtitle: Text(
                    e.description,
                    overflow: TextOverflow.ellipsis,
                    maxLines: 3,
                  ),
                  leading: CircleAvatar(
                    backgroundImage: NetworkImage(e.imageUrl),
                  ),
                ),
              ))
          .toList(),
    );
  }
}
